package com.yilin.commons.encrypt;

import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class SM2WithSM3Utils {

    private static BouncyCastleProvider bc = new BouncyCastleProvider();
    public static String sign(String apiSecret, String content) {
        try {
            Signature signature = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(), bc);
            KeyFactory keyFact = KeyFactory.getInstance("EC", bc);
            byte[] ss= Base64.decode(apiSecret);
            PKCS8EncodedKeySpec sds=   new PKCS8EncodedKeySpec((ss));
            PrivateKey privateKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(apiSecret)));
            signature.initSign(privateKey);
            byte[] plainText = content.getBytes(StandardCharsets.UTF_8);
            signature.update(plainText);
            return org.python.bouncycastle.util.encoders.Base64.toBase64String(signature.sign());
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }


}